<?php
/***************************************************************************
   Coppermine 1.3.1 for CPG-Dragonfly™
  **************************************************************************
   Port Copyright (c) 2004-2005 CPG Dev Team
   http://dragonflycms.com/
  **************************************************************************
   v1.1 (c) by Grégory Demar http://coppermine.sf.net/
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
****************************************************************************/
if (!defined('CPG_NUKE')) { die("You can't access this file directly..."); }
define('USERMGR_PHP', true);
define('PROFILE_PHP', true);
require("modules/{$module_name}/include/load.inc");
if (!GALLERY_ADMIN_MODE) cpg_die(_ERROR, ACCESS_DENIED);

function list_users()
{
	global $CONFIG, $lang_usermgr_php;

	$K    = Dragonfly::getKernel();
	$L10N = $K->L10N;
	$OUT  = $K->OUT;
	$SQL  = $K->SQL;

	$sort_codes = array(
		'name_a' => 'username ASC',
		'name_d' => 'username DESC',
		'group_a' => 'group_name ASC',
		'group_d' => 'group_name DESC',
		'reg_a' => 'user_id ASC',
		'reg_d' => 'user_id DESC',
		'pic_a' => 'pic_count ASC',
		'pic_d' => 'pic_count DESC',
		'disku_a' => 'disk_usage ASC',
		'disku_d' => 'disk_usage DESC',
	);

	$sort   = (isset($sort_codes[$_GET->raw('sort')]) ? $_GET['sort'] : 'reg_d');
	$limit  = 25;
	$offset = max(0,$_GET->uint('page')-1) * $limit;

	$OUT->user_search = mb_strtolower($_GET->raw('q'));
	$where = $OUT->user_search ? "WHERE user_nickname_lc LIKE '%{$SQL->escape_string($OUT->user_search)}%'" : '';

	$result = $SQL->query("SELECT
		user_id,
		username,
		user_email,
		group_name,
		user_active_cp,
		user_level,
		COUNT(pid) pic_count,
		SUM(total_filesize) disk_usage,
		(group_quota * 1000) group_quota /* is stored in KB */
	FROM {$CONFIG['TABLE_USERS']} u
	LEFT JOIN {$CONFIG['TABLE_USERGROUPS']} g ON user_group_cp = group_id
	LEFT JOIN {$CONFIG['TABLE_ALBUMS']} a ON category = " . FIRST_USER_CAT . " + user_id
	LEFT JOIN {$CONFIG['TABLE_PICTURES']} p ON p.aid = a.aid
	{$where}
	GROUP BY user_id, username, user_email, group_name, user_active_cp, user_level, group_quota
	ORDER BY {$sort_codes[$sort]}");

	$user_count = $result->num_rows;
	if (!$user_count) cpg_die(_CRITICAL_ERROR, ERR_NO_USERS);

	$sort_options = array();
	foreach ($sort_codes as $key => $value) {
		$sort_options[] = array(
		'value'    => $key,
		'selected' => ($key == $sort),
		'label'    => $lang_usermgr_php[$key],
		);
	}
	$OUT->sort_options = $sort_options;

	$OUT->users = array();
	$result->data_seek($offset);
	while (0<$limit--)
	{
		$user = $result->fetch_assoc();
		if (!$user) { break; }
		if (!$user['user_active_cp'] || $user['user_level']==0 ) $user['group_name'] = NULL;
		$user['disk_usage_perc'] = 100 * $user['disk_usage'] / max(1,$user['group_quota']);
		$user['disk_usage_txt']  = $L10N->filesizeToHuman((int)$user['disk_usage']);
		$user['group_quota_txt'] = $L10N->filesizeToHuman((int)$user['group_quota']);
		$user['gallery_uri'] = $user['pic_count'] ? URL::index('&cat=' . ($user['user_id'] + FIRST_USER_CAT)) : null;
		$user['edit_uri']    = URL::index("&amp;file=usermgr&amp;edit={$user['user_id']}");
		$user['delete_uri']  = URL::index("&amp;file=delete&amp;user={$user['user_id']}");
		$OUT->users[] = $user;
	}
	$result->free();

	$OUT->pagination   = new \Poodle\Pagination(URL::index('&file=usermgr&page=${page}&sort='.$sort), $user_count, $offset, $limit);
	$OUT->user_on_page = sprintf(U_USER_ON_P_PAGES, $user_count, $OUT->pagination->count());
	$OUT->uri_new_user = URL::admin('admin&op=users#add-user');
	$OUT->display('coppermine/usermgr');
}

function edit_user($user_id)
{
	global $db, $CONFIG, $lang_usermgr_php, $lang_yes, $lang_no;

	$user_data = $db->uFetchAssoc("SELECT username, user_active_cp, user_group_cp, user_group_list_cp FROM {$CONFIG['TABLE_USERS']} WHERE user_id = {$user_id}");
	if (!$user_data) cpg_die(_CRITICAL_ERROR, ERR_UNKNOWN_USER);

	$yes_selected = ($user_data['user_active_cp']) ? 'selected' : '';
	$no_selected = (!$user_data['user_active_cp']) ? 'selected' : '';

	$group_list = $db->uFetchAll("SELECT group_id, group_name FROM {$CONFIG['TABLE_USERGROUPS']} ORDER BY group_name");
	$sel_group = $user_data['user_group_cp'];
	$user_group_list = explode(',', $user_data['user_group_list_cp']);

	echo '<form method="post" action="">
	<table>
	<thead>
		<tr>
			<th colspan=2">'.MODIFY_USER.'</th>
		</tr>
	</thead>
	<tbody>
		<tr>
			<td width="40%">'.U_NAME.'</td>
			<td width="60%">'.$user_data['username'].'</td>
		</tr>
		<tr>
			<td>'.USER_ACTIVE_CP.'</td>
			<td>
				<select name="user_active_cp">
					<option value="1" '.$yes_selected.'>'.YES.'</option>
					<option value="0" '.$no_selected.'>'.NO.'</option>
				</select>
			</td>
		</tr>
		<tr>
			<td>'.USER_GROUP_CP.'</td>
			<td valign="top">
				<select name="user_group_cp">';

	$group_cb = '';
	foreach ($group_list as $group) {
		echo '
					<option value="' . $group['group_id'] . '"' . ($group['group_id'] == $sel_group ? ' selected' : '') . '>' . $group['group_name'] . "</option>";
		$checked = (user_ingroup($group['group_id'], $user_group_list)) ? 'checked' : '';
		$group_cb .= '<input name="group_list[]" type="checkbox" value="' . $group['group_id'] . '" ' . $checked . '> ' . $group['group_name'] . "<br />\n";
	}

	echo '
				</select><br />
				'.$group_cb.'
			</td>
		</tr>
	</tbody>
	<tfoot>
		<tr>
			<td></td>
			<td><button type="submit">save</button></td>
		</tr>
	</tfoot>
	</table>
</form>
';

}

if (isset($_GET['edit']))
{
	$user_id = $_GET->uint('edit');
	if (USER_ID == $user_id && !can_admin()) { cpg_die(_ERROR, ERR_EDIT_SELF); }
	if ('POST' === $_SERVER['REQUEST_METHOD'])
	{
		global $CONFIG;

		$user_group_cp = $_POST->uint('user_group_cp');
		$group_list = isset($_POST['group_list']) ? $_POST['group_list'] : '';
		$user_group_list = array();
		if (is_array($group_list)) {
			foreach ($group_list as $group) {
				if ($group != $user_group_cp) { $user_group_list[] = intval($group); }
			}
		}

		Dragonfly::getKernel()->SQL->exec("UPDATE {$CONFIG['TABLE_USERS']} SET
			user_active_cp     = ".intval($_POST->bool('user_active_cp')).",
			user_group_cp      = ".$user_group_cp.",
			user_group_list_cp = ".$db->quote(implode(',',$user_group_list))."
		WHERE user_id = {$user_id}");

		URL::redirect(URL::index("&file=usermgr"));
	}
	pageheader(U_TITLE);
	edit_user($user_id);
	pagefooter();
}
else
{
	pageheader(U_TITLE);
	list_users();
	pagefooter();
}
